package dongze.com.ckdj.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.greendao.query.Join;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.BR;
import dongze.com.ckdj.R;
import dongze.com.ckdj.adapter.NamePlateTodayAdapter;
import dongze.com.ckdj.dagger.component.UserComponent;
import dongze.com.ckdj.data.entity.response.BrandResponse;
import dongze.com.ckdj.data.entity.response.GetNamePlateTodayResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.data.entity.response.VehicleNumberResponse;
import dongze.com.ckdj.databinding.InformationItemSpinnerBinding;
import dongze.com.ckdj.databinding.InformationItemTextBinding;
import dongze.com.ckdj.databinding.VehicleNumberItemBinding;
import dongze.com.ckdj.databinding.model.InformationItemSpinnerModel;
import dongze.com.ckdj.databinding.model.InformationItemTextModel;
import dongze.com.ckdj.databinding.model.VehicleNumberModel;
import dongze.com.ckdj.fragment.NamePlateFragment;
import dongze.com.ckdj.fragment.OKFragment;
import dongze.com.ckdj.fragment.OutlineFragment;
import dongze.com.ckdj.map.MapUtil;
import dongze.com.ckdj.persistence.dao.DaoSession;
import dongze.com.ckdj.persistence.dao.NamePlateUploadRecord;
import dongze.com.ckdj.persistence.dao.NamePlateUploadRecordDao;
import dongze.com.ckdj.persistence.dao.ServerUploadTask;
import dongze.com.ckdj.persistence.dao.ServerUploadTaskDao;
import dongze.com.ckdj.persistence.dao.State;
import dongze.com.ckdj.util.MyLog;
import dongze.com.ckdj.util.Util;
import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.functions.Action;
import io.reactivex.observers.DisposableObserver;


/**
 * Created by fanqwz on 2017/8/18.
 */

public class NamePlateActivity extends BaseActivity {
    private static final String TAG = NamePlateActivity.class.getSimpleName();
    private final int BACK_PRESSED_MSG = 1026;
    @BindView(R.id.basic_info_container)
    GridLayout mBasicInfoLayout;
    @BindView(R.id.vehicle_number_container)
    ViewGroup mVehicleNumberContainer;
    @BindView(R.id.progress)
    FrameLayout progressBar;
    @BindView(R.id.finished_list)
    ListView listView;
    @BindView(R.id.unfinished_list)
    ListView unListView;
    @BindView(R.id.finished_num)
    TextView totalCount;
    @BindView(R.id.unfinished_num)
    TextView unTotalCount;
    @BindView(R.id.finished_list_empty_view)
    View finished_list_empty_view;
    @BindView(R.id.unfinished_list_empty_view)
    View unfinished_list_empty_view;
    @BindView(R.id.fragment_container)
    View fragmentContainer;
    MapUtil mapUtil;
    @Inject
    User mUser;
    @Inject
    DaoSession daoSession;
    android.os.Handler mHandler;
    String mCurrentVehicleNumber;
    int progressCount = 0;
    List<BrandResponse> brands;
    boolean exitOnNamePlateOk = false;

    InformationItemTextModel mTimeModel = new InformationItemTextModel();
    InformationItemTextModel mUserModel = new InformationItemTextModel();
    VehicleNumberModel mVehicleNumberModel = new VehicleNumberModel();
    InformationItemSpinnerModel mBrandModel = new InformationItemSpinnerModel();
    private DisposableObserver mPendingDisposable;
    List<VehicleNumberResponse> vehicList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name_plate);
        ButterKnife.bind(this);

        fragmentContainer.setVisibility(View.GONE);
        listView.setEmptyView(finished_list_empty_view);
        unListView.setEmptyView(unfinished_list_empty_view);


        mapUtil = new MapUtil(getAppCompenent());
        mHandler = new Handler(getMainLooper());

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(mTimeReceiver, intentFilter);

        if (getComponent(UserComponent.class) != null) {
            getComponent(UserComponent.class).inject(this);
        } else {
            finish();
            return;
        }

        initData(getIntent());

        mBrandModel.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (propertyId == BR.position) {
                    try {
                        Util.setPreference(NamePlateActivity.this, Util.PREF_SELECTED_BRAND, brands.get(mBrandModel.getPosition()).getBrand_code());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mBasicInfoLayout.removeAllViews();
        mVehicleNumberContainer.removeAllViews();
        initData(intent);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mTimeReceiver);
        mapUtil.dispose();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.name_plate_activity_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.workload) {
            Intent intent = new Intent(getApplicationContext(), NamePlateWorkLoadActivity.class);

            if (mBrandModel.getValues() != null) {
                intent.putExtra("brandcode", brands.get(mBrandModel.getPosition()).getBrand_code());
                intent.putExtra("brandname", mBrandModel.getValues()[mBrandModel.getPosition()]);
            } else if (brands != null && brands.size() > 0) {
                intent.putExtra("brandcode", brands.get(0).getBrand_code());
                intent.putExtra("brandname", brands.get(0).getBrand_name());
            }

            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
//        if (!TextUtils.isEmpty(mCurrentVehicleNumber)) {
//            new AlertDialog.Builder(this)
//                    .setMessage("铭牌图片上传未完成，仍要退出吗？")
//                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            mHandler.sendMessage(mHandler.obtainMessage(BACK_PRESSED_MSG));
//                            mCurrentVehicleNumber = null;
//                            NamePlateActivity.this.onBackPressed();
//                        }
//                    })
//                    .setNegativeButton(android.R.string.no, null)
//                    .create()
//                    .show();
//        } else {

        if (mHandler.hasMessages(BACK_PRESSED_MSG)) {
            super.onBackPressed();
        } else {
            Toast.makeText(this, "再次按下返回键退出当前页面", Toast.LENGTH_SHORT).show();
            mHandler.sendMessageDelayed(mHandler.obtainMessage(BACK_PRESSED_MSG), 1500);
        }
//        }
    }

    private void initData(Intent intent) {
        if (mUser == null) {
            MyLog.e(TAG, "onCreate: user null, activity finished");
            new AlertDialog.Builder(this)
                    .setMessage("user null")
                    .setCancelable(false)
                    .setNegativeButton("exit", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .create()
                    .show();
            return;
        }

        if (intent == null)
            intent = getIntent();

        String vin = intent.getStringExtra("vin");
        String brandCode = intent.getStringExtra("brand_code");
        String brandName = intent.getStringExtra("brand_name");
        exitOnNamePlateOk = !TextUtils.isEmpty(vin);

        mTimeModel.setKey("当前时间");
        mTimeModel.setValue(Util.getCurrentTime(this));
        addBasicInfoItem(mTimeModel);

        mUserModel.setKey("登陆人员");
        mUserModel.setValue(mUser.getRemark() + "-" + mUser.getUser_name());
        addBasicInfoItem(mUserModel);


        if (exitOnNamePlateOk) {
            brands = new ArrayList<>(1);
            BrandResponse brandResponse = new BrandResponse();
            brandResponse.setBrand_code(brandCode);
            brandResponse.setBrand_name(brandName);
            brands.add(brandResponse);

            InformationItemTextModel mBrandModelText = new InformationItemTextModel();
            mBrandModelText.setKey("品牌");
            mBrandModelText.setValue(brandName);
            addBasicInfoItem(mBrandModelText);

            InformationItemTextModel m = new InformationItemTextModel();
            m.setValue(vin);
            addVehicleNumberText(m);
            showNamePlateFragment(vin, "");
        } else {
            mBrandModel.setKey("品牌");
            addBrandName(mBrandModel);
            loadBrands();

            addVehicleNumber(mVehicleNumberModel);
        }

        queryNamePlate(mUser.getUser_no());
//        getUnFinishedNamePlate();
        if (exitOnNamePlateOk) {
        }
        mVehicleNumberModel.setVisibility(View.VISIBLE);
    }


    private void addBrandName(InformationItemSpinnerModel model) {
        InformationItemSpinnerBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_spinner, mBasicInfoLayout, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemSpinner(model);
//        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.name_plate_brand_width), ViewGroup.LayoutParams.WRAP_CONTENT);
//        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
//        params.setMargins(margin, margin, margin, margin);
//        params.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
        int count = mBasicInfoLayout.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1, 0.5f), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mBasicInfoLayout.addView(binding.getRoot(), params);
    }

    private void addVehicleNumber(VehicleNumberModel model) {
        VehicleNumberItemBinding vehicleNumberItemBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.vehicle_number_item, mVehicleNumberContainer, false);
        model.setKey("车架号");
        model.setOnItemClickListener(mOnVehicleNumberClick);
        vehicleNumberItemBinding.setInformationItemAutoCompleteTextModel(model);
        model.addOnPropertyChangedCallback(mOnVehicleNumberChangedListener);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        params.gravity = Gravity.CENTER;
        mVehicleNumberContainer.addView(vehicleNumberItemBinding.getRoot(), params);
    }

    private void addVehicleNumberText(InformationItemTextModel model) {
        InformationItemTextBinding vehicleNumberItemBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_text, mVehicleNumberContainer, false);
        model.setKey("车架号");
        vehicleNumberItemBinding.setVehicleInformationItemText(model);
        model.addOnPropertyChangedCallback(mOnVehicleNumberChangedListener);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        params.gravity = Gravity.CENTER;
        mVehicleNumberContainer.addView(vehicleNumberItemBinding.getRoot(), params);
    }

    private void addBasicInfoItem(InformationItemTextModel model) {
        InformationItemTextBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_text, mBasicInfoLayout, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemText(model);
        int count = mBasicInfoLayout.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1, 0.5f), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mBasicInfoLayout.addView(binding.getRoot(), params);
    }

    private void showProgressBar() {
        progressCount++;

        if (progressCount > 0) {
            getWindow().getDecorView().setEnabled(false);
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    private void hideProgressBar() {
        progressCount--;

        if (progressCount <= 0) {
            getWindow().getDecorView().setEnabled(true);
            progressBar.setVisibility(View.GONE);
        }
    }

    private void loadBrands() {
        mapUtil.getBrands("1",
                new DisposableObserver<List<BrandResponse>>() {
                    @Override
                    protected void onStart() {
                        super.onStart();
                        showProgressBar();
                    }

                    @Override
                    public void onNext(List<BrandResponse> value) {
                        String pref = Util.getPreference(NamePlateActivity.this, Util.PREF_SELECTED_BRAND, null);
                        String[] entries = new String[value.size()];

                        for (int i = 0; i < value.size(); i++) {
                            entries[i] = value.get(i).getBrand_name();
                        }

                        mBrandModel.setValues(entries);
                        mBrandModel.setPosition(0);
                        brands = value;

                        for (int i = 0; i < value.size(); i++) {
                            if (TextUtils.equals(value.get(i).getBrand_code(), pref))
                                mBrandModel.setPosition(i);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        MyLog.e(TAG, "onError: ", e);
                        new AlertDialog.Builder(NamePlateActivity.this)
                                .setMessage(e.getMessage())
                                .create()
                                .show();
                        hideProgressBar();
                    }

                    @Override
                    public void onComplete() {
                        hideProgressBar();
                    }
                });
    }

    // 已上传
    private void queryNamePlate(String user) {
        mapUtil.getNamePlateToday(user,
                new DisposableObserver<GetNamePlateTodayResponse>() {
                    @Override
                    public void onNext(GetNamePlateTodayResponse value) {
                        totalCount.setText(String.valueOf(value.getImgsNum()));
                        listView.setAdapter(new NamePlateTodayAdapter(value));
                    }

                    @Override
                    public void onError(Throwable e) {
                        new AlertDialog.Builder(NamePlateActivity.this)
                                .setMessage(e.getMessage())
                                .create()
                                .show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    // 未上传
    private void getUnFinishedNamePlate() {

        QueryBuilder qb = daoSession
                .getNamePlateUploadRecordDao()
                .queryBuilder()
                .where(NamePlateUploadRecordDao.Properties.User.eq(mUser.getUser_name()));
        Join unfinish = qb.join(NamePlateUploadRecordDao.Properties.Id, ServerUploadTask.class, ServerUploadTaskDao.Properties.RecordId);
        unfinish.where(ServerUploadTaskDao.Properties.State.notEq(State.Finished.ordinal()));
        List<NamePlateUploadRecord> mLocalList = qb.list();

        if (mLocalList != null && mLocalList.size() > 0) {
            GetNamePlateTodayResponse value = new GetNamePlateTodayResponse();
            value.setImgs(new ArrayList<GetNamePlateTodayResponse.NamePlate>());
            for (NamePlateUploadRecord record : mLocalList) {
                GetNamePlateTodayResponse.NamePlate data = new GetNamePlateTodayResponse.NamePlate();
                data.setVin(record.getVin());
                data.setImg(record.getImagePath());
                data.setuTime(record.getTime());
                value.getImgs().add(data);
            }
            value.setImgsNum(mLocalList.size());
            unTotalCount.setText(String.valueOf(value.getImgsNum()));
            unListView.setAdapter(new NamePlateTodayAdapter(value));
        } else {
            unTotalCount.setText("0");
        }
    }

    private void showNamePlateFragment(final String vin, final String carColor) {
        if (TextUtils.equals(vin, mCurrentVehicleNumber)) {
            mVehicleNumberModel.setValue(null);
            Toast.makeText(this, "车架号重复", Toast.LENGTH_SHORT).show();
            return;
        }

        MyLog.v(TAG, "showNamePlateFragment: " + vin);

        final Runnable showRunnable = new Runnable() {
            @Override
            public void run() {
                if (exitOnNamePlateOk) {
                    mVehicleNumberModel.setValue(vin);
                } else {
                    mVehicleNumberModel.setHint(vin);
                    mVehicleNumberModel.setValue(null);
                }
                mVehicleNumberModel.setCarColor(carColor);


                mCurrentVehicleNumber = vin;
                final NamePlateFragment namePlateFfragment = new NamePlateFragment();
                io.reactivex.Completable npo = io.reactivex.Completable.create(new CompletableOnSubscribe() {
                    @Override
                    public void subscribe(final CompletableEmitter e) throws Exception {
                        namePlateFfragment.setData(vin, mUser, daoSession);
                        namePlateFfragment.setListener(new NamePlateFragment.OnNamePlateOKListener() {
                            @Override
                            public void onNamePalteOK(String uri) {
                                queryNamePlate(mUser.getUser_no());
                                getSupportFragmentManager().beginTransaction()
                                        .replace(R.id.name_plate_fragment_container, new OKFragment())
                                        .commitAllowingStateLoss();
                                e.onComplete();
                            }
                        });
                    }
                });

                final OutlineFragment outlineFragment = new OutlineFragment();
                io.reactivex.Completable oto = io.reactivex.Completable.create(new CompletableOnSubscribe() {
                    @Override
                    public void subscribe(final CompletableEmitter e) throws Exception {
                        outlineFragment.setData(vin, mUser, daoSession);
                        outlineFragment.setListener(new OutlineFragment.OnOulineOKListener() {
                            @Override
                            public void onOutLineOK(String uri) {
                                queryNamePlate(mUser.getUser_no());
                                getSupportFragmentManager().beginTransaction()
                                        .replace(R.id.outline_fragment_container, new OKFragment())
                                        .commitAllowingStateLoss();
                                e.onComplete();
                            }
                        });
                    }
                });

                Completable.merge(Arrays.asList(npo, oto))
                        .subscribe(new Action() {
                            @Override
                            public void run() throws Exception {
                                if (exitOnNamePlateOk) {
                                    finish();
                                } else {
//                    getUnFinishedNamePlate();
                                    mVehicleNumberModel.setValue(null);
                                    mCurrentVehicleNumber = null;
                                    mVehicleNumberModel.setHint(null);
                                    getSupportFragmentManager().beginTransaction()
                                            .remove(getSupportFragmentManager().findFragmentById(R.id.name_plate_fragment_container))
                                            .remove(getSupportFragmentManager().findFragmentById(R.id.outline_fragment_container))
                                            .commitAllowingStateLoss();
                                    fragmentContainer.setVisibility(View.GONE);
                                }
                            }
                        });

                fragmentContainer.setVisibility(View.VISIBLE);
                getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.name_plate_fragment_container, namePlateFfragment)
                        .replace(R.id.outline_fragment_container, outlineFragment)
                        .commitAllowingStateLoss();

            }
        };

//        if (!TextUtils.isEmpty(mCurrentVehicleNumber)) {
//            new AlertDialog.Builder(this)
//                    .setMessage("当前车架号数据未上传，取消上传吗？")
//                    .setPositiveButton("不取消", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            mVehicleNumberModel.setValue(null);
//                        }
//                    })
//                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            showRunnable.run();
//                        }
//                    })
//                    .create()
//                    .show();
//        } else {
        showRunnable.run();
//        }
    }

    private Observable.OnPropertyChangedCallback mOnVehicleNumberChangedListener = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            if (propertyId == BR.value) {
                mHandler.removeCallbacks(mGetAutoCompleteDateRunnable);
                mHandler.postDelayed(mGetAutoCompleteDateRunnable, 300);
            }
        }
    };

    private Runnable mGetAutoCompleteDateRunnable = new Runnable() {
        @Override
        public void run() {
            MyLog.d(TAG, "run:mGetAutoCompleteDateRunnable");

            if (mVehicleNumberModel.getValue() == null
                    || mVehicleNumberModel.getValue().length() <= 3
                    || mVehicleNumberModel.getValue().equals(mCurrentVehicleNumber)
                    || mBrandModel.getValues() == null
                    || brands == null)
                return;

            if (mPendingDisposable != null && !mPendingDisposable.isDisposed()) {
                mPendingDisposable.dispose();
            }

            mPendingDisposable = new DisposableObserver<List<VehicleNumberResponse>>() {
                @Override
                protected void onStart() {
                    super.onStart();
//                    showProgressBar();
                    mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<查询中......>", null)));
                }

                @Override
                public void onNext(List<VehicleNumberResponse> value) {
                    MyLog.d(TAG, "onNext: mGetAutoCompleteDateRunnable");
                    List<Pair<String, String>> entries = new ArrayList<>(value.size());
                    for (int i = 0; i < value.size(); i++) {
                        Pair<String, String> p = new Pair<>(value.get(i).getVin(), value.get(i).getBrand_name());
                        entries.add(p);
                    }
                    vehicList.clear();
                    vehicList.addAll(value);
                    mVehicleNumberModel.setEntries(entries);
                    if (value.size() == 1) {
                        // 只有一个结果自动填充并开始做下一步查询
                        mVehicleNumberModel.setEntries(null);
                        showNamePlateFragment(entries.get(0).first, value.get(0).getColor());
                    } else if (value.size() == 0) {
                        mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<找不到车架号>", null)));
                    }
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<查询出错>", null)));
//                    hideProgressBar();
                }

                @Override
                public void onComplete() {
//                    hideProgressBar();
                }
            };

            mapUtil.mapInformationItemAutoCompleteTextModelWithVehicleNumberResponse(
                    mVehicleNumberModel.getValue(),
                    brands.get(mBrandModel.getPosition()).getBrand_code(), ""
                    , mPendingDisposable);
        }
    };


    AdapterView.OnItemClickListener mOnVehicleNumberClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // start get detail info
            MyLog.d(TAG, "onItemClick: ");
            mHandler.removeCallbacks(mGetAutoCompleteDateRunnable);

            //check
            try {
                if (mVehicleNumberModel.getValue() == null
                        || !mVehicleNumberModel.getValue().equals(
                        mVehicleNumberModel.getEntries().get(position).first)
                        || (mVehicleNumberModel.getValue().startsWith("<") && mVehicleNumberModel.getValue().endsWith(">"))) {
                    MyLog.e(TAG, "onItemClick: check data consistency failed");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            mVehicleNumberModel.setEntries(null);
            showNamePlateFragment(mVehicleNumberModel.getValue(), vehicList.get(position).getColor());
        }
    };
    BroadcastReceiver mTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mTimeModel.setValue(Util.getCurrentTime(NamePlateActivity.this));
            }
        }
    };
}
